10 ROS 2 - Writing a simple service and client

Writing a simple service and client

  • Open new terminal and run:
cs
ros2 pkg create --build-type ament_python py_srvcli --dependencies rclpy example_interfaces
  • The --dependencies argument will automatically add the necessary dependency lines to package.xml. example_interfaces is the package that includes the .srv file you will need to structure your requests and responses. But what is the service from example_interfaces?  How find the information about it?
ros2 interface list
  • Open another terminal and run:
ros2 interface list

Pasted image 20251012100855.png

Finding Service info

  • In the same terminal and run:
ros2 interface show example_interfaces/srv/AddTwoInts

Pasted image 20251012101037.png

  • To find the location, in the same terminal run this command:
ros2 pkg prefix example_interfaces
  • In the same terminal and run:
cs
cd py_srvcli/py_srvcli
touch service_member_function.py
sudo chmod u+x  service_member_function.py
  • In the same terminal and run:
sudo gedit  service_member_function.py
  • Copy and paste the code into it.
from example_interfaces.srv import AddTwoInts

import rclpy
from rclpy.node import Node


class MinimalService(Node):

    def __init__(self):
        super().__init__("minimal_service")
        self.srv = self.create_service(
            AddTwoInts, "add_two_ints", self.add_two_ints_callback
        )

    def add_two_ints_callback(self, request, response):
        response.sum = request.a + request.b
        self.get_logger().info("Incoming request\na: %d b: %d" % (request.a, request.b))

        return response


def main(args=None):
    rclpy.init(args=args)

    minimal_service = MinimalService()

    rclpy.spin(minimal_service)

    rclpy.shutdown()


if __name__ == "__main__":
    main()

Add an entry point

•In filer explorer, go to “ros2_ws/src/py_srvcli”, open “setup.py”, add this line:

'service = py_srvcli.service_member_function:main',

Like this:
Pasted image 20251012101417.png

  • In the same terminal and run:
cs
cd py_srvcli/py_srvcli
touch client_member_function.py
sudo chmod u+x  client_member_function.py
  • In the same terminal and run:
sudo gedit  client_member_function.py
  • Copy and paste the code into it.
import sys

from example_interfaces.srv import AddTwoInts
import rclpy
from rclpy.node import Node


class MinimalClientAsync(Node):

    def __init__(self):
        super().__init__("minimal_client_async")
        self.cli = self.create_client(AddTwoInts, "add_two_ints")
        while not self.cli.wait_for_service(timeout_sec=1.0):
            self.get_logger().info("service not available, waiting again...")
        self.req = AddTwoInts.Request()

    def send_request(self, a, b):
        self.req.a = a
        self.req.b = b
        self.future = self.cli.call_async(self.req)
        rclpy.spin_until_future_complete(self, self.future)
        return self.future.result()


def main(args=None):
    rclpy.init(args=args)

    minimal_client = MinimalClientAsync()
    response = minimal_client.send_request(int(sys.argv[1]), int(sys.argv[2]))
    minimal_client.get_logger().info(
        "Result of add_two_ints: for %d + %d = %d"
        % (int(sys.argv[1]), int(sys.argv[2]), response.sum)
    )

    minimal_client.destroy_node()
    rclpy.shutdown()


if __name__ == "__main__":
    main()

 Add an entry point

  • In filer explorer, go to “ros2_ws/src/py_srvcli”, open “setup.py”, add this line:
'client = py_srvcli.client_member_function:main',

Like this:Pasted image 20251012101824.png

  • It’s good practice to run rosdep in the root of your workspace (ros2_ws) to check for missing dependencies before building:
cw
rosdep install -i --from-path src --rosdistro foxy –y
  • To build the package, open another terminal and run:
cb
sb
  • Open another terminal and run:
ros2 run py_srvcli service
  • Open another terminal and run:
ros2 run py_srvcli client 2 3

Pasted image 20251012102013.png